package com.cw.jeeyt.service.directive;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.util.StringUtils;

import com.cw.jeeyt.common.enums.EnumOperateFlag;
import com.cw.jeeyt.common.utils.HttpKit;
import com.cw.jeeyt.service.bo.system.SystemDictCacheBo;
import com.cw.jeeyt.service.utils.DictUtils;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateModel;

/**
 * 页面上数据字典自定义标签
 * 思路：页面上数据字典的字典项通过这种方式异步加载，
* @author chenw
* @version 1.0.0
 */
public class PageDictDirective implements TemplateDirectiveModel {
    /** 数据字典描述 */
    private TemplateModel dictDesc = null;
     /** 数据字典key */
    private TemplateModel dictKey = null;
     /** 数据字典类型 text,select,radio,checkbox */
    private TemplateModel dictType = null;
     /** 数据字典标签名 */
    private TemplateModel dictName = null;
     /** 数据字典值 */
    private TemplateModel dictValue = null;
     /** 是否必填 */
    private TemplateModel required = null;
     /** 数据字典样式 */
    private TemplateModel dictClass = null;
     /** 数据字典label样式 */
    private TemplateModel labelClass = null;
     /** 页面类型 form,index */
    private TemplateModel pageType = null;
     /** 默认值 */
    private TemplateModel defaultValue = null;
     /** 方法 */
    private TemplateModel dictMethod = null;
     /** 是否只读 */
    private TemplateModel readOnly = null;
     /** 是否置灰 */
    private TemplateModel disabled = null;
     /** 不需要加载的字典项 */
    private TemplateModel subList = null;
     /** 控制只显示的字典项 */
    private TemplateModel chooseList = null;
    private String operation = "";
    private StringBuilder dictInfo = null;
    private List<SystemDictCacheBo> itemList = null;

    /**
     * 初始化页面数据字典元素
     */
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars,
        TemplateDirectiveBody body) throws IOException {
        HttpServletRequest request = HttpKit.getRequest();
        operation = request.getParameter("operation");
        Writer out = env.getOut();
        env.setOutputEncoding("utf-8");
        dictInfo = new StringBuilder("");
        //数据字典描述
        dictDesc = (TemplateModel) params.get("dict_desc");
        //数据字典key
        dictKey = (TemplateModel) params.get("dict_key");
        //数据字典类型 text,select,radio,checkbox
        dictType = (TemplateModel) params.get("dict_type");
        //数据字典标签名
        dictName = (TemplateModel) params.get("dict_name");
        //数据字典值
        dictValue = (TemplateModel) params.get("dict_value");
        //是否必填
        required = (TemplateModel) params.get("required");
        //数据字典样式
        dictClass = (TemplateModel) params.get("dict_class");
        //数据字典标签样式
        labelClass = (TemplateModel) params.get("label_class");
        //页面类型 form,index
        pageType = (TemplateModel) params.get("page_type");
        //默认值
        defaultValue = (TemplateModel) params.get("default_value");
        //方法
        dictMethod = (TemplateModel) params.get("dict_method");
        //是否只读
        readOnly = (TemplateModel) params.get("readonly");
        //是否置灰
        disabled = (TemplateModel) params.get("disabled");
        //控制只显示的字典项
        chooseList = (TemplateModel) params.get("choose_list");
        //不需要加载的字典项
        subList = (TemplateModel) params.get("sub_list");
        String labelDesc = "";
        String indexLabelClass = "";
        String formLabelClass = "";
        if (dictDesc != null) {
            labelDesc = dictDesc.toString();
        } else {
            labelDesc = "未知标签";
        }
        if (pageType != null && pageType.toString()
            .equals("index")) {
            if (labelClass != null) {
                indexLabelClass = labelClass.toString();
            } else {
                indexLabelClass = "col-md-1 col-sm-1 col-xs-1 text-right";
            }
            dictInfo.append("<div class='" + indexLabelClass + "'>");
            dictInfo.append("<label class='control-label h-form-label'>" + labelDesc + "：</label>");
            dictInfo.append("</div>");
        } else {
            if (labelClass != null) {
                formLabelClass = labelClass.toString();
            } else {
                formLabelClass = "col-md-1 col-sm-1 col-xs-1 text-right";
            }
            dictInfo.append("<label class='" + formLabelClass + "'>" + labelDesc + "：</label>");
        }
        if (dictClass != null) {
            dictInfo.append("<div class='" + dictClass.toString() + "'>");
        } else {
            if (pageType != null && pageType.toString()
                .equals("index")) {
                dictInfo.append("<div class='col-md-2 col-sm-2 col-xs-2'>");
            } else {
                dictInfo.append("<div class='col-sm-8'>");
            }
        }
        //加载数据字典选项
        Map<String, Object> dictParams = new HashMap<>();
        if (dictKey != null) {
            dictParams.put("dictKey", dictKey.toString());
        }
        if (chooseList != null) {
            dictParams.put("chooseList", chooseList.toString());
        }
        if (subList != null) {
            dictParams.put("subList", subList.toString());
        }
        SystemDictCacheBo dictData = DictUtils.getDictInfo(dictKey.toString());
        if (dictData != null) {
            itemList = dictData.getChildList();
        }else{
            itemList = DictUtils.getDataDicItem(dictParams);
        }
        if (dictType != null) {
            switch (dictType.toString()) {
                case "select":
                    initSelectData();
                    break;
                case "text":
                    initTextData();
                    break;
                case "checkbox":
                    initCheckBoxData();
                    break;
                case "radio":
                    initRadioData();
                    break;
                default:
                    break;
            }
        }
        dictInfo.append("</div>");
        //设置必输的*符号
        if (required != null && (required.toString()
            .equals("required") || required.toString()
            .equals("true"))) {
            dictInfo.append("<div class='col-sm-1'>");
            dictInfo.append("<span class='required'>*</span>");
            dictInfo.append("</div>");
        }
        out.write(dictInfo.toString());
    }

    /**
     * 设置radio数据
     */
    private void initRadioData() {
        if (itemList != null && !itemList.isEmpty()) {
            for (SystemDictCacheBo itemInfo : itemList) {
                String itemName = itemInfo.getItemName();
                String itemValue = itemInfo.getItemValue();
                String itemComment = itemInfo.getDictComment();
                dictInfo.append(
                    "<input type='radio'  id='" + dictName + "' name='" + dictName + "' value='" + itemValue + "'");
                if (required != null && (required.toString()
                    .equals("required") || required.toString()
                    .equals("true"))) {
                    dictInfo.append(" required='required'");
                }
                if (dictValue != null && !StringUtils.isEmpty(dictValue.toString())) {
                    if (dictValue.toString()
                        .equals(itemValue)) {
                        dictInfo.append(" checked='checked'");
                    }
                } else {
                    if (defaultValue != null && defaultValue.toString()
                        .equals(itemValue)) {
                        dictInfo.append(" checked='checked'");
                    }
                }
                if (EnumOperateFlag.VIEW.getCode()
                    .equals(operation)) {
                    dictInfo.append(" disabled='disabled'");
                } else {
                    if (disabled != null && (disabled.toString()
                        .equals("disabled") || disabled.toString()
                        .equals("true"))) {
                        dictInfo.append("disabled='disabled'");
                    }
                }
                if (dictMethod != null) {
                    dictInfo.append(" onclick='" + dictMethod + "'");
                }
                dictInfo.append("'/><label for='" + dictName + "' style='margin-right:20px'>" + itemComment + "</label>");
            }
        }
    }

    /**
     * 设置checkbox数据
     */
    private void initCheckBoxData() {
        if (itemList != null && !itemList.isEmpty()) {
            for (SystemDictCacheBo itemInfo : itemList) {
                String itemName = itemInfo.getItemName();
                String itemValue = itemInfo.getItemValue();
                String itemComment = itemInfo.getDictComment();
                //dictInfo.append("<div class='checkbox checkbox-inline'>");
                dictInfo.append(
                    "<input type='checkbox' id='" + dictName + "' name='" + dictName + "' value='" + itemValue + "'");
                if (required != null && required.toString()
                    .equals("required") || required.toString()
                    .equals("true")) {
                    dictInfo.append(" required='required'");
                }
                if (dictValue != null && !StringUtils.isEmpty(dictValue.toString())) {
                    if (dictValue.toString()
                        .indexOf(itemValue) > -1) {
                        dictInfo.append(" checked='checked'");
                    }
                } else {
                    if (defaultValue != null && defaultValue.toString()
                        .indexOf(itemValue) > -1) {
                        dictInfo.append(" checked='checked'");
                    }
                }
                if (EnumOperateFlag.VIEW.getCode()
                    .equals(operation)) {
                    dictInfo.append(" disabled='disabled'");
                } else {
                    if (disabled != null) {
                        dictInfo.append(" disabled='disabled'");
                    }
                }
                if (dictMethod != null) {
                    dictInfo.append(" onclick='" + dictMethod.toString() + "'");
                }
                dictInfo.append("'/><label for='" + dictName.toString() + "' style='margin-right:10px'>" + itemComment + "</label>");
            }
        }
    }

    /**
     * 初始化select数据
     */
    private void initTextData() {

        String textValue = "";
        if (itemList != null && !itemList.isEmpty()) {
            for (SystemDictCacheBo itemInfo : itemList) {
                String itemName = itemInfo.getItemName();
                String itemValue = itemInfo.getItemValue();
                if (dictValue != null && !StringUtils.isEmpty(dictValue.toString())) {
                    if (dictValue.toString()
                        .indexOf(itemValue) > -1) {
                        textValue += itemName + ",";
                    }
                } else {
                    if (defaultValue != null && defaultValue.toString()
                        .indexOf(itemValue) > -1) {
                        textValue += itemName + ",";
                    }
                }

            }
        }
        if (!StringUtils.isEmpty(textValue)) {
            textValue = textValue.substring(0, textValue.length() - 1);
        }
        dictInfo.append("<input type='text' id='" + dictName + "' name='" + dictName + "' value='" + textValue
            + "' class='form-control'");
        if (required != null && (required.toString()
            .equals("required") || required.toString()
            .equals("true"))) {
            dictInfo.append(" required='required'");
        }
        if (EnumOperateFlag.VIEW.getCode()
            .equals(operation)) {
            dictInfo.append(" readonly='readonly'");
        } else {
            if (readOnly != null && (readOnly.toString()
                .equals("readonly") || readOnly.toString()
                .equals("true"))) {
                dictInfo.append(" readonly='readonly'");
            }
        }
        dictInfo.append("/>");
    }

    /**
     * 初始化select数据
     *
     * @return
     */
    private void initSelectData() {
        if (pageType != null && pageType.toString()
            .equals("index")) {
            dictInfo.append("<select id='" + dictName.toString() + "' name='" + dictName.toString() + "'");
        } else {
            dictInfo.append(
                "<select id='" + dictName.toString() + "' name='" + dictName.toString() + "' class='form-control'");
        }
        //设置只读
        if (EnumOperateFlag.VIEW.getCode()
            .equals(operation)) {
            dictInfo.append(" disabled='disabled'");
        } else {
            if (disabled != null && (disabled.toString()
                .equals("disabled") || disabled.toString()
                .equals("true"))) {
                dictInfo.append(" disabled='disabled'");
            }
            if (readOnly != null && (readOnly.toString()
                .equals("readonly") || readOnly.toString()
                .equals("true"))) {
                dictInfo.append(" disabled='disabled'");
            }
        }
        //设置必填
        if (required != null && (required.toString()
            .equals("required") || required.toString()
            .equals("true"))) {
            dictInfo.append(" required='required'");
        }
        //设置方法
        if (dictMethod != null) {
            dictInfo.append(" onchange='" + dictMethod.toString() + "'>");
        } else {
            dictInfo.append(">");
        }
        dictInfo.append("<option value=''>--请选择--</option>");
        if (itemList != null && !itemList.isEmpty()) {
            for (SystemDictCacheBo itemInfo : itemList) {
                //如果value不为空，则看是否有设置defaultValue
                String itemValue = itemInfo.getItemValue();
                String itemComment = itemInfo.getDictComment();
                if (dictValue != null && !StringUtils.isEmpty(dictValue.toString())) {
                    if (dictValue.toString()
                        .equals(itemValue)) {
                        dictInfo.append(
                            "<option value='" + itemValue + "' selected='selected'>" + itemComment + "</option>");
                    } else {
                        dictInfo.append("<option value='" + itemValue + "'>" + itemComment + "</option>");
                    }
                } else {
                    //如果设置了默认值，则
                    if (defaultValue != null && defaultValue.toString()
                        .equals(itemValue)) {
                        dictInfo.append(
                            "<option value='" + defaultValue.toString() + "' selected='selected'>" + itemComment
                                + "</option>");
                    } else {
                        dictInfo.append("<option value='" + itemValue + "'>" + itemComment + "</option>");
                    }
                }
            }
        }
        dictInfo.append("</select>");
    }
}
